#include "SFMLTextureManager.h"
#include "..\Debug\DebugLog.h"

using namespace vn;

SFMLTextureManager::SFMLTextureManager(void)
{
	m_mode = RESOURCE_MODE_FILE;
	m_loadTexFptr[RESOURCE_MODE_STREAM] = &SFMLTextureManager::loadFromStream;
	m_loadTexFptr[RESOURCE_MODE_FILE] = &SFMLTextureManager::loadFromFile;
}

SFMLTextureManager::~SFMLTextureManager(void)
{
	unloadAllTextures();
}

void SFMLTextureManager::unloadTexture(const std::string& p_id)
{
	auto it = m_textures.find(p_id);
	if (it != m_textures.end())
		m_textures.erase(it);
}

void SFMLTextureManager::unloadTexture(const sf::Texture& p_texture)
{
	for (auto it = m_textures.begin(); it != m_textures.end(); it++)
	{
		if (&it->second == &p_texture)
		{
			m_textures.erase(it);
			break;
		}
	}
}

void SFMLTextureManager::unloadAllTextures()
{
	m_textures.clear();
}

const sf::Texture& SFMLTextureManager::loadTexture(const std::string& p_id, const std::string& p_filepath, bool p_repeat, bool p_smooth)
{
	return (this->*m_loadTexFptr[m_mode])(p_id, p_filepath, p_repeat, p_smooth);
}

inline const sf::Texture& SFMLTextureManager::loadFromFile(const std::string& p_id, const std::string& p_filepath, bool p_repeat, bool p_smooth)
{
	auto it = m_textures.find(p_id);
	if (it != m_textures.end())
		return it->second;
	sf::Texture texture;
	texture.loadFromFile(p_filepath);
	texture.setRepeated(p_repeat);
	texture.setSmooth(p_smooth);
	m_textures.insert(std::make_pair(p_id, texture));
	return m_textures[p_id];
}

inline const sf::Texture& SFMLTextureManager::loadFromStream(const std::string& p_id, const std::string& p_filepath, bool p_repeat, bool p_smooth)
{
	auto it = m_textures.find(p_id);
	if (it != m_textures.end())
		return it->second;
	
	if (!PHYSFS_exists(p_filepath.c_str()))
	{
		Debug::log("ERROR LOADING TEXTURE FROM STREAM: cannot find " + p_filepath);
		abort();
	}

	sf::physfs stream(p_filepath.c_str());
	sf::Texture texture;
	texture.loadFromStream(stream);
	texture.setRepeated(p_repeat);
	texture.setSmooth(p_smooth);
	m_textures.insert(std::make_pair(p_id, texture));
	return m_textures[p_id];
}

void SFMLTextureManager::resourceMode(int p_mode)
{
	if (p_mode == RESOURCE_MODE_STREAM || p_mode == RESOURCE_MODE_FILE)
		m_mode = p_mode;
}